import React, { useState, useEffect }from 'react';
import { Button, Table, Space, Input, Modal, Breadcrumb, Select, Form, Switch, Checkbox, message} from 'antd';
import { DatabaseOutlined, SearchOutlined, RedoOutlined } from '@ant-design/icons';
import { getUserList, getUserById, updateUser, deleteUser } from '../../service/user';
import { useNavigate, useParams } from 'react-router-dom';
import dayjs from 'dayjs';
const { confirm } = Modal;

const { Option } = Select;

const Users = () => {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [modalContent, setModalContent] = useState('');
    const [modalTitle, setModalTitle] = useState('');
    const [selectedRole, setSelectedRole] = useState('');

    const [userData, setUserData] = useState([]);
    const [filteredData, setFilteredData] = useState([]);

    const { id } = useParams();
    const [form] = Form.useForm();
    const navigate = useNavigate();

    // 发送接口请求/user/list
    useEffect(() => {
      fetchUserList();
    }, []);

    const fetchUserList = () => {
      getUserList().then((response) => {
        console.log(response.data);
        setUserData(response.data.result);
        setFilteredData(response.data.result);
      });
    };

    // 发送接口请求/user/get/:id
    // useEffect(() => {
    //   if (id) {
    //     getUserById(id).then((response) => {
    //       const { code, result } = response.data;
    //       if (code === 1 && result) {
    //         const data = { ...result};
    //         setUserData(data);
    //         console.log(data);
    //         form.setFieldsValue(data);
    //       }
    //     });
    //   }
    // }, []);

    // 实现点击不同按钮后弹窗
    const showModal = (content, record) => {
      getUserById(record.id).then((response) => {
          const { code, result } = response.data;
          if (code === 1 && result) {
            const data = { ...result, createDate: dayjs(result.createDate), lastLogin: dayjs(result.lastLogin)};
            setUserData(data);
            console.log(data);
            form.setFieldsValue(data);
          }
        });
  
      setModalContent(
          <Form form={form} onFinish={onFinish}>
            <Form.Item name="id" label="编号" hidden></Form.Item>
              <Form.Item name="username" label="账号" hidden/>
              <Form.Item name="name" label="姓名" hidden/>
              <Form.Item name="mailbox" label="邮箱" hidden/>
              <Form.Item name="password" label="密码" hidden/>
              <Form.Item name="createDate" label="创建时间" hidden/>
              <Form.Item name="lastLogin" label="最后登录" hidden/>
              <Form.Item name="ifused" label="是否启用" valuePropName="checked" hidden/>
              <Form.Item name="role" label="角色">
              <Select style={{ width: 200, margin:'20px'}} onChange={setSelectedRole}>
                <Option value="product">商品管理员</Option>
                <Option value="order">订单管理员</Option>
                <Option value="super">超级管理员</Option>
              </Select>
              </Form.Item>
          </Form>
        );
      setModalTitle('分配角色');
      
      setIsModalOpen(true);
    };

    const onFinish =(values)=>{
      const data = {
          ...userData,
          ...values,
          createDate: values.createDate.format('YYYY-MM-DD HH:mm:ss'),
          lastLogin: values.lastLogin.format('YYYY-MM-DD HH:mm:ss')
        };
    
        updateUser(values.id, data).then((response) => {
          console.log(response.data);
          const { code, msg } = response.data;
          if (code === 1) {
            message.success(msg);
            setIsModalOpen(false);
          }
      });
    }

    const handleOk = () => {
      form.submit();
    };

    const handleCancel = () => {
      setIsModalOpen(false);
    };

    // 实现删除
    const handleDelete = (id) => {
      confirm({
        title: '确认删除吗',
        okText: '确认',
        cancelText: '取消',
        onOk(){
          return deleteUser(id).then((response) => {
            const { code, msg } = response.data;
            if (code === 1) {
              message.success(msg);
              fetchUserList();
            }
          });
        },
      });
    };

    // 实现查询和重置功能
    const [searchText, setSearchText] = useState('');

    const handleSearch = () => {
      const filtered = userData.filter(user =>
          user.username.toLowerCase().includes(searchText.toLowerCase())
      );
      setFilteredData(filtered);
    };

    const handleReset = () => {
        setSearchText('');
        setFilteredData(userData);
    };

    // 是否启用switch按钮
    const handleSwitchChange = (record, checked) => {
      console.log('Switch changed:', record.id, checked); // 打印调试信息
      // 更新本地状态中的用户数据
      const newData = filteredData.map(item => {
          if (item.id === record.id) {
              return { ...item, ifused: checked };
          }
          return item;
      });
      setFilteredData(newData);

      // 如果需要，这里也可以发送请求到服务器以更新数据库中的数据
      // 发送API请求代码（例如使用axios）
      // axios.post('/api/updateUser', { id: record.id, ifused: checked }).then(...)
  };

    // 数据属性名
    const columns = [
      {
        title: '编号',
        dataIndex: 'id',
        key: 'id'
      },
      {
        title: '账号',
        dataIndex: 'username',
        key: 'username'
      },
      {
          title: '姓名',
          dataIndex: 'name',
          key: 'name',
      },
      {
          title: '邮箱',
          dataIndex: 'mailbox',
          key: 'mailbox',
      },
      {
          title: '添加时间',
          dataIndex: 'createDate',
          key: 'createDate',
      },
      {
          title: '最后登录',
          dataIndex: 'lastLogin',
          key: 'lastLogin',
      },
      {
          title: '是否启用',
          dataIndex: 'ifused',
          key: 'ifused',
          render: (text, record) => (
            <Switch checked={record.ifused} 
                    onChange={(checked) => handleSwitchChange(record, checked)} 
                    style={{ width: '40px'}} />
          ),
      },
      {
          title: '操作',
          key: 'operation',
          render: (text, record) => (
            <Space size="">
              <Button type='link' style={{width: '80px', marginLeft:'-20px'}} 
                      onClick={() => showModal('setRole', record)}>分配角色</Button>
              <Button type='link' style={{width: '50px'}} onClick={() => navigate('/user/edit/'+record.id)}>编辑</Button>
              <Button type='link' style={{width: '50px'}} onClick={() => handleDelete(record.id)}>删除</Button>
            </Space>
        ),
      },
    ];

    return (
        <div className='datalist-container'>
            <Breadcrumb
              style={{
                margin: '16px 0',
              }}
            >
              <Breadcrumb.Item>权限</Breadcrumb.Item>
              <Breadcrumb.Item>用户</Breadcrumb.Item>
            </Breadcrumb>
            <div className='select' 
                style={{
                    width: '100%',
                    height: '100px',
                    display: 'flex',
                    border: '1px solid #ccc',
                    borderRadius: '5px'
                }}>
                    <SearchOutlined style={{ marginLeft: '20px', marginTop: '-50px'}}/>
                    <span style={{ 
                        // flex: 1, 
                        marginLeft: '10px',
                        fontSize: '16px',
                        marginTop: '12px',
                        }}>
                        筛选搜索
                    </span> 
                    <span style={{ 
                        // flex: 1, 
                        marginLeft: '-20px',
                        fontSize: '16px',
                        marginTop: '50px'
                        }}>
                        输入搜索：
                    </span> 
                    <Input size='large' placeholder='账号/姓名' 
                      value={searchText} onChange={(e) => setSearchText(e.target.value)}
                      style={{
                          width: '200px',
                          height: '30px',
                          marginTop: '45px'
                    }}/>
                    <Button icon={<RedoOutlined />}
                            style={{
                                height: '40px',
                                width: '100px',
                                marginLeft: '50px',
                                marginTop: '40px'
                            }}
                            onClick={handleReset}>
                        重置
                    </Button>
                    <Button type="primary" 
                            icon={<SearchOutlined />} 
                            style={{
                                height: '40px',
                                width: '100px',
                                marginLeft: '10px',
                                marginTop: '40px'
                            }}
                            onClick={handleSearch}>
                        查询
                    </Button>
            </div>
            <div className='datalist-header'
                style={{
                    width: '100%',
                    height: '50px',
                    display: 'flex',
                    border: '1px solid #ccc',
                    borderRadius: '5px',
                    marginTop: '20px'
                }}>
                <DatabaseOutlined style={{ marginLeft: '8px' }} /> 
                <span style={{ 
                        flex: 1, 
                        marginLeft: '10px',
                        fontSize: '16px',
                        marginTop: '12px'
                        }}>
                    数据列表
                </span> 
                <Button htmlType='submit' 
                        style={{ 
                            width: '80px',
                            height: '30px',
                            marginRight: '20px',
                            marginTop: '10px' 
                        }}
                        onClick={()=> navigate('/user/add')}>
                    添加
                </Button>
            </div>
            <div className='datalist-body'>
                <Table
                    columns={columns}
                    dataSource={filteredData}
                    rowKey={'id'}
                    style={{ marginTop: '20px'}}
                />
                <Modal title={modalTitle} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                    {modalContent}
                </Modal>
            </div>
        </div>
    )
};

export default Users;